const service = require('../../services/note-service');
const messages = require('../../common/messages');
const timeHelper = require('../../common/time-helper');
const RefreshTrigger = require('../../common/refresh-trigger');

Page({
  data: {
    query: '',
    items: [],
  },
  refreshTrigger: null,
  onLoad() {
    this.refreshTrigger = new RefreshTrigger(this.doRefreshItem);
  },

  onReady() {},

  onShow() {
    this.refreshTrigger.refresh();
  },

  buildItemUi(item) {
    return {
      ...item,
      createAtUi: timeHelper.timestampToDate(item.createAtUi),
    };
  },
  onQueryInput(e) {
    this.setData({
      query: e.detail.value,
    });
  },
  doRefreshItem() {
    const q = this.data ? this.data.query : '';
    service
      .queryAll(q)
      .then((res) => {
        const newItems = res.data.map(this.buildItemUi);
        this.setData({
          items: newItems,
        });
      })
      .catch(messages.showError);
  },

  onHide() {},

  onUnload() {},

  onPullDownRefresh() {},

  onReachBottom() {},

  onShareAppMessage() {},

  doShowDetail(e) {
    const { id } = e.currentTarget.dataset;
    this.refreshTrigger.navigateTo({ url: `/pages/note-item/index?id=${id}` });
  },
});
